package com.app.community.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.app.community.mapper.HomeMapper;
import com.app.community.model.entity.AliyunClient;
import com.app.community.model.entity.User;
import com.app.community.util.AliyunOSSUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @Author SakuraA6
 * @Description TODO
 * @Date 2020/10/21 14:19
 **/
@Slf4j
@Service
public class HomeService {

    @Autowired
    HomeMapper homeMapper;

    AliyunClient ossClient = new AliyunClient();

    AliyunOSSUtils aliyunOSSUtils = new AliyunOSSUtils();

    // 创建OSSClient实例。
    OSS oss = new OSSClientBuilder().build(ossClient.getEndpoint(), ossClient.getAccessKeyId(), ossClient.getAccessKeySecret());

    @Cacheable(cacheNames = {"userInfo"})
    public User searchUserInfo(String userId) {
        return homeMapper.searchUserInfo(userId);
    }

    public void updateAvatar(MultipartFile avatar, String userId) {
        String suffix = avatar.getOriginalFilename().substring(avatar.getOriginalFilename().lastIndexOf("."));
        log.info("上传文件后缀：" + suffix);
        try {
            String url = aliyunOSSUtils.uploadUserImgToOSS(oss, avatar.getInputStream(), userId, System.currentTimeMillis() + suffix);
            homeMapper.updateUserAvatar(url, userId);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void updatecoverPic(MultipartFile coverPic, String userId) {
        String suffix = coverPic.getOriginalFilename().substring(coverPic.getOriginalFilename().lastIndexOf("."));
        log.info("上传文件后缀：" + suffix);
        try {
            String url = aliyunOSSUtils.uploadUserImgToOSS(oss, coverPic.getInputStream(), userId, System.currentTimeMillis() + suffix);
            homeMapper.updateUserCoverPic(url, userId);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void updateNickName(String nickName, String userId) {
        homeMapper.updateUserNickname(nickName, userId);
    }

    public void updateSex(String sex, String userId) {
        homeMapper.updateUserSex(sex, userId);
    }

    public void updateIntro(String introduction, String userId) {
        homeMapper.updateUserIntro(introduction, userId);
    }

    public void updateSubject(String subject, String userId) {
        homeMapper.updateUserSubject(subject, userId);
    }

    public void updateYear(String year, String userId) {
        homeMapper.updateUserYear(year, userId);
    }
}
